package com.ad.pet.common.data.http;

/**
 * Created by SEELE on 2018/3/26.
 */

import java.util.ArrayList;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

/**
 * 特殊的自动管理Cookies
 */
public class CookiesManager implements CookieJar {

    private final List<Cookie> allCookies = new ArrayList<>();



    private static List<Cookie> cookies;

    public static List<Cookie> getCookies() {
        return cookies != null ? cookies : new ArrayList<Cookie>();
    }

    public static void setCookies(List<Cookie> cookies) {
        CookiesManager.cookies = cookies;
    }

    public synchronized void saveFromResponse(HttpUrl url, List<Cookie> cookies)
    {
        allCookies.addAll(cookies);

        setCookies(cookies);
    }


    @Override
    public synchronized List<okhttp3.Cookie> loadForRequest(HttpUrl url)
    {
        List<Cookie> result = new ArrayList<>();
        for (Cookie cookie : allCookies)
        {
            if (cookie.matches(url))
            {
                result.add(cookie);
            }
        }
        return result;
    }
}
